import ReactDOM from 'react-dom'
import { createStore } from '@reduxjs/toolkit'
import { devToolsEnhancer } from '@redux-devtools/extension'
import React from 'react'
/*
state = {
  todos:[
    {id, text, completed},
    ...
  ],
  filter: string, // all / active / completed
  count: 0
}
*/
const filter = (state = 'all', action) => {
  switch (action.type) {
    // {type: 'filter', payload: 'active'}
    case 'filter':
      return action.payload
    default:
      return state
  }
}
const todos = (state = [], action) => {
  switch (action.type) {
    // type=add_todo, payload={id, text}
    case 'add_todo':
      return [...state, { ...action.payload, completed: false }]
    // type=remove_todo, payload=id
    case 'remove_todo':
      return state.filter((todo) => todo.id !== action.payload)
    // type=toggle_todo, payload=id
    case 'toggle_todo':
      const todoIndex = state.findIndex((todo) => todo.id === action.payload)
      const newTodo = {
        ...state[todoIndex],
        completed: !state[todoIndex].completed,
      }
      return [
        ...state.slice(0, todoIndex),
        newTodo,
        ...state.slice(todoIndex + 1),
      ]
    // type=filter
    default:
      return state
  }
}
const count = (state = 0, action) => {
  switch(action.type) {
    case 'add_todo':
    case 'toggle_todo':
      return state + 1
    default:
      return state
  }
}

const todoApp = (state = {}, action) => {
  return {
    todos: todos(state.todos, action),
    filter: filter(state.filter, action),
    todoActionCount:count(state.todoActionCount, action)
  }
}
const store = createStore(
  todoApp,
  {
    todos: [
      { id: 1, text: '看电影', completed: false },
      { id: 2, text: '遛狗', completed: true },
      { id: 3, text: '跑步', completed: false },
    ],
  },
  devToolsEnhancer()
)
window.store = store

function getVisibleTodos(todos, filter) {
  // selector
  switch (filter) {
    case 'all':
      return todos
    case 'active':
      return todos.filter((todo) => !todo.completed)
    case 'completed':
      return todos.filter((todo) => todo.completed)
    default:
      throw new Error('无效的filter值：'+filter)
  }
}

let id = 10
class TodoApp extends React.Component {
  render() {
    const { todos, filter } = store.getState()
    const visibleTodos = getVisibleTodos(todos, filter)
    return (
      <>
        <form
          onSubmit={(e) => {
            e.preventDefault()
            const text = e.target.text.value.trim()
            store.dispatch({
              type: 'add_todo',
              payload: {
                text,
                id: id++,
              },
            })
            e.target.text.value = ''
            e.target.text.focus()
          }}
        >
          <input type="text" name="text" autoComplete="off" />
          <button>+待办事项</button>
        </form>
        <ul>
          {visibleTodos.map((todo) => (
            <li
              key={todo.id}
              style={{
                textDecoration: todo.completed ? 'line-through' : 'none',
              }}
              onClick={() =>
                store.dispatch({
                  type: 'toggle_todo',
                  payload: todo.id,
                })
              }
            >
              {todo.text}
            </li>
          ))}
        </ul>
        <p>
          <a
            href="#all"
            style={{
              color: filter === 'all' ? 'red' : 'blue',
            }}
            onClick={(e) => {
              e.preventDefault()
              store.dispatch({ type: 'filter', payload: 'all' })
            }}
          >
            全部
          </a>{' '}
          <a
            href="#active"
            style={{
              color: filter === 'active' ? 'red' : 'blue',
            }}
            onClick={(e) => {
              e.preventDefault()
              store.dispatch({ type: 'filter', payload: 'active' })
            }}
          >
            未完成
          </a>{' '}
          <a
            href="#completed"
            style={{
              color: filter === 'completed' ? 'red' : 'blue',
            }}
            onClick={(e) => {
              e.preventDefault()
              store.dispatch({ type: 'filter', payload: 'completed' })
            }}
          >
            已完成
          </a>{' '}
        </p>
      </>
    )
  }
}
function render() {
  ReactDOM.render(<TodoApp />, document.getElementById('root'))
}
store.subscribe(render)
render()
